package com.leoman.welfare.service.impl;

import com.leoman.adsindex.dao.AdsIndexDao;
import com.leoman.adsindex.entity.AdsIndex;
import com.leoman.banner.dao.BannerDao;
import com.leoman.banner.entity.Banner;
import com.leoman.common.service.impl.GenericManagerImpl;
import com.leoman.entity.Configue;
import com.leoman.entity.Constant;
import com.leoman.entity.FileBo;
import com.leoman.floatwin.dao.FloatWinDao;
import com.leoman.floatwin.entity.FloatWin;
import com.leoman.image.dao.ExpressionDao;
import com.leoman.image.entity.Expressions;
import com.leoman.utils.DateUtils;
import com.leoman.utils.FileUtil;
import com.leoman.utils.ZipUtil;
import com.leoman.welfare.dao.UserWelfareCountDao;
import com.leoman.welfare.dao.UserWelfareDao;
import com.leoman.welfare.dao.WelfareDao;
import com.leoman.welfare.entity.UserWelfare;
import com.leoman.welfare.entity.UserWelfareCount;
import com.leoman.welfare.entity.Welfare;
import com.leoman.welfare.service.WelfareService;
import com.leoman.work.dao.WorkSurroundDao;
import com.leoman.work.entity.WorkSurround;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartRequest;

import java.io.IOException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by 蔡琦 on 2016/6/29 0029.
 */
@Service
public class WelfareServiceImpl extends GenericManagerImpl<Welfare, WelfareDao> implements WelfareService {

    @Autowired
    private WelfareDao welfareDao;

    @Autowired
    private UserWelfareDao userWelfareDao;

    @Autowired
    private ExpressionDao expressionDao;

    @Autowired
    private BannerDao bannerDao;

    @Autowired
    private AdsIndexDao adsIndexDao;

    @Autowired
    private FloatWinDao floatWinDao;

    @Autowired
    private UserWelfareCountDao userWelfareCountDao;

    @Autowired
    private WorkSurroundDao workSurroundDao;

    @Override
    public Page<Welfare> page(Integer pageNum, Integer pageSize) {
        return welfareDao.findAll(new PageRequest(pageNum - 1, pageSize, Sort.Direction.DESC, "status", "updateDate"));
    }

    @Override
    public List<Welfare> findByType(Integer type) {
        return welfareDao.findByType(type);
    }

    @Override
    @Transactional
    public Integer saveAll(Long welfareId,
                           String title,
                           String subtitle,
                           Integer type,
                           Integer storeNum,
                           Integer changeNum,
                           String startDate,
                           String endDate,
                           Integer limit,
                           Integer coin,
                           String length,
                           Integer coin1,
                           Integer experience,
                           String description1,
                           Integer coin2,
                           String description2,
                           Integer coin3,
                           String description3,
                           String url4,
                           Integer coin5,
                           String url5,
                           MultipartRequest multipartRequest) throws IOException, ParseException {
        String unZipPath = "";
        MultipartFile multipartFile2 = null;
        Welfare welfare;

        if (welfareId == null) {
            welfare = new Welfare();
            welfare.setStatus(0);
            welfare.setCreateDate(System.currentTimeMillis());
        } else {
            welfare = welfareDao.findOne(welfareId);
        }

        MultipartFile multipartFile = multipartRequest.getFile("cover");
        if (null != multipartFile) {
            FileBo fileBo = FileUtil.save(multipartFile, true);
            welfare.setCover(fileBo.getPath());
            welfare.setSuolue(fileBo.getSuoluePath());
        }

        welfare.setTitle(title);
        welfare.setSubTitle(subtitle);
        welfare.setType(type);
        welfare.setStoreNum(storeNum);
        welfare.setChangeNum(changeNum);
        welfare.setStartDate(DateUtils.stringToLong(startDate, "yyyy-MM-dd hh:mm:ss"));
        welfare.setEndDate(DateUtils.stringToLong(endDate, "yyyy-MM-dd hh:mm:ss"));
        welfare.setConditions(limit);
        welfare.setUpdateDate(System.currentTimeMillis());

        if (type.equals(Constant.WELFARE_TYPE_000)) {

            // 保存铃声
            MultipartFile multipartFile1 = multipartRequest.getFile("url");

            // 验证音乐格式
            String originalFileName = multipartFile1.getOriginalFilename().toLowerCase();
            String fileType = originalFileName.substring(originalFileName.indexOf("."));

            List<String> list = new ArrayList<>();
            list.add(".mp3");
            list.add(".wav");
            list.add(".ogg");

            if (!list.contains(fileType)) {
                return 2;
            }
            if (multipartFile1 != null) {
                FileBo fileBo = FileUtil.save(multipartFile1, false);
                welfare.setUrl(fileBo.getPath());
            }
            welfare.setCoin(coin);
            welfare.setLength(length);

        } else if (type.equals(Constant.WELFARE_TYPE_001)) {

            // 保存经验值
            welfare.setCoin(coin1);
            welfare.setExper(experience);
            welfare.setDescription(description1);

        } else if (type.equals(Constant.WELFARE_TYPE_002)) {

            // 保存实物
            welfare.setCoin(coin2);
            welfare.setDescription(description2);

        } else if (type.equals(Constant.WELFARE_TYPE_003)) {

            // 保存表情包
            multipartFile2 = multipartRequest.getFile("url3");
            if (null != multipartFile2) {

                if (multipartFile2.getSize() > 10 * 1024 * 1024) {
                    return 2;
                }
                FileBo fileBo = FileUtil.save(multipartFile2, false);
                welfare.setUrl(fileBo.getPath());
                unZipPath = fileBo.getName();
            }
            welfare.setCoin(coin3);
            welfare.setDescription(description3);

        } else if (type.equals(Constant.WELFARE_TYPE_004)) {

            // 保存商城购买
            welfare.setUrl(url4);

        } else if (type.equals(Constant.WELFARE_TYPE_005)) {

            // 保存游戏兑换码
            welfare.setCoin(coin5);
            welfare.setUrl(url5);

        }

        welfareDao.save(welfare);

        // 处理表情包并保存
        return dealAndSaveEmotion(type, multipartFile2, welfare, unZipPath, welfareId);
    }

    @Override
    @Transactional
    public Integer deleteWelfare(Long welfareId) {
        Welfare welfare = welfareDao.findOne(welfareId);

        // 是否链接到广告banner
        List<Banner> bannerList = bannerDao.findByTypeAndWorkId(Constant.POSITION_005, welfareId);
        if (bannerList.size() != 0) {
            return 2;
        }

        // 是否链接到首页推荐
        List<AdsIndex> adsIndexList = adsIndexDao.findByTypeAndWorkId(Constant.POSITION_005, welfareId);
        if (adsIndexList.size() != 0) {
            return 2;
        }

        // 是否链接到浮窗广告
        List<FloatWin> floatWinList = floatWinDao.findByTypeAndWorkId(Constant.POSITION_005, welfareId);
        if (floatWinList.size() != 0) {
            return 2;
        }

        // 该福利是否有作品的周边购买
        List<WorkSurround> workSurroundList = workSurroundDao.findByWelfareId(welfareId);
        if (workSurroundList.size() != 0) {
            return 2;
        }

        // 先删除所有的福利兑换记录
        List<UserWelfare> userWelfareList = userWelfareDao.findByWelfareId(welfareId);
        for (UserWelfare userWelfare : userWelfareList) {
            if (welfare.getType().equals(Constant.WELFARE_TYPE_003) && userWelfare.getWelfare().getId().equals(welfareId)) {
                // 表情包已兑换，不能删除
                return 3;
            } else {
                userWelfareDao.delete(userWelfare);
            }
        }

        // 删除所有的用户兑换福利数量记录
        List<UserWelfareCount> userWelfareCountList = userWelfareCountDao.findListByWelfareId(welfareId);
        for (UserWelfareCount userWelfareCount : userWelfareCountList) {
            userWelfareCountDao.delete(userWelfareCount);
        }

        welfareDao.delete(welfare);

        return 1;
    }

    @Override
    public List<Welfare> findByStick() {
        return welfareDao.findByStick();
    }

    // 处理表情包并保存
    public Integer dealAndSaveEmotion(Integer type, MultipartFile multipartFile, Welfare welfare, String unZipPath, Long welfareId) throws IOException {
        try {
            if (type.equals(Constant.WELFARE_TYPE_003) && null != multipartFile) {
                // 解压缩表情包
                String[] paths = ZipUtil.unZipFiles(Configue.getUploadPath() + welfare.getUrl(), Configue.getUploadPath() + "zip/file/" + unZipPath);

                // 将解压出来的表情包区分为png格式和gif格式
                List<String> pngList = new ArrayList<>();
                List<String> gifList = new ArrayList<>();

                for (String path : paths) {
                    if (StringUtils.isEmpty(path)) {
                        continue;
                    }
                    if (path.contains(".png")) {
                        pngList.add(path);
                    }
                    if (path.contains(".gif")) {
                        gifList.add(path);
                    }
                }

                // 查询表情包，如果有，删除原先的表情包
                List<Expressions> list = expressionDao.findListByParentId(welfare.getId());
                if (null != list && list.size() > 0) {
                    for (Expressions expressions : list) {
                        expressionDao.delete(expressions);
                    }
                }

                // 将解压出来的表情包存入数据库
                Expressions expressions;
                for (int i = 0; i < pngList.size(); i++) {
                    expressions = new Expressions();
                    expressions.setParentId(welfare.getId());
                    expressions.setName(pngList.get(i).substring(paths[i].lastIndexOf("/") + 1, pngList.get(i).length() - 4));
                    expressions.setGifUrl(gifList.get(i).replace(Configue.getUploadPath(), ""));
                    expressions.setPngUrl(pngList.get(i).replace(Configue.getUploadPath(), ""));

                    expressionDao.save(expressions);
                }
            }

            return 1;
        } catch (IOException e) {
            if (null == welfareId) {
                welfareDao.delete(welfare);
            }

            e.printStackTrace();

            return 0;
        }
    }

}
